'use strict';

const path = require('path')
const pkgDir = require('pkg-dir').sync
const pathExists = require('path-exists').sync
const npminstall = require('npminstall')
const { isObject } = require('@lio-imooc-cli-dev/utils')
const formatPath = require('@lio-imooc-cli-dev/format-path')
const { getDefaultRegistry, getNpmLatestVersion } = require('@lio-imooc-cli-dev/get-npm-info')

class Package {
    constructor (options) {
        console.log('Package constructor')

        if (!options) {
            throw new Error('Package类的options参数不能为空！')
        }
        if (!isObject(options)) {
            throw new Error('Package类的options参数必须为对象！')
        }
        // Package的目标路径
        this.targetPath = options.targetPath
        // 缓存package的路径
        this.storeDir = options.storeDir
        // package的name
        this.packageName = options.packageName
        // package的Version
        this.packageVersion = options.packageVersion
        // package的缓存目录前缀
        this.cacheFilePathPrefix = this.packageName.replace('/', '_')
    }

    async prepare() {
        if (this.packageVersion === 'latest') {
            this.packageVersion = await getNpmLatestVersion(this.packageName)
        }
        console.log('this.packageVersion =======>', this.packageVersion)

    }

    // _@lio-imooc-cli-dev_init@1.1.2@@lio-imooc-cli-dev/
    get cacheFilePath() {
        return path.resolve(this.storeDir, `_${this.cacheFilePathPrefix}@${this.packageVersion}@${this.packageName}`)
    }

    // 判断当前的Package是否存在
    async exists() {
        if (this.storeDir) {
            await this.prepare()
            console.log('this.cacheFilePath', this.cacheFilePath)
            return pathExists(this.cacheFilePath)
        } else {
            return pathExists(this.targetPath)
        }

    }

    // 安装Package
    async install () {
        await this.prepare()

        return npminstall({
            root: this.targetPath,
            storeDir: this.storeDir,
            registry: getDefaultRegistry(true),
            pkgs: [
                {
                    name: this.packageName,
                    version: this.packageVersion
                }
            ]
        })
    }

    // 更新Package
    update() {

    }

    // 获取入口文件的路径
    // lio-imooc-cli-dev init --targetPath D:\software\java\workspace\lio-imooc-cli-dev\commands\init\lib --debug test-project --force
    getRootFilePath () {
        // 1、获取package.json所在目录 - pkg-dir
        const dir = pkgDir(this.targetPath)
        if (dir) {
            // 2、读取package.json - required()
            const pkgFile = require(path.resolve(dir, 'package.json'))
            console.log('pkgFile =======>', pkgFile)
            // 3、寻找main/lib
            if (pkgFile && pkgFile.main) {
                // 4、路径的兼容(maxOs/windows)
                return formatPath(path.resolve(dir, pkgFile.main))
            }
        }
        return null
    }
}

module.exports = Package;

